package org.bbd.cumi.dao;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

import org.bbd.cumi.bean.AccessExample;
import org.bbd.cumi.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

public class AccessDao extends BaseDao {
	
	   @SuppressWarnings("unchecked")
	public List selectByExample(AccessExample example) {
	        List list = getSqlMapClientTemplate().queryForList("access.abatorgenerated_selectByExample", example);
	        return list;
	    }

	private void calculateSummary()
	{
		getTransactionTemplate().execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus ts) {
				JdbcTemplate jt = new JdbcTemplate();				
				jt.setDataSource(AccessDao.this.getDataSource());
				PreparedStatement pst;
				InputStream is=this.getClass().getResourceAsStream("/org/bbd/cumi/dao/Summary.sql");
				String sql="";
				try {
					String str=StringUtil.readAsString(is).toString();
					String arySql[]=str.split(";");
					for(int i=0;i<arySql.length;i++)
					{
						sql=arySql[i];
						if(sql.trim().length()  > 0)
						{
							Statement stmt=jt.getDataSource().getConnection().createStatement();
							logger.debug("Executing: " + sql);
							stmt.execute(sql);
						};
					}
					
					is.close();
				} catch (Exception e) {
				
					e.printStackTrace();
					System.err.println("SQL containing error: " + sql);
				}
				
				return null;
			}});
	}
	   
	public void importLog(final String proxy,final InputStream is) {
		getTransactionTemplate().execute(new TransactionCallback() {			
			public Object doInTransaction(TransactionStatus ts) {
				JdbcTemplate jt = new JdbcTemplate();				
				jt.setDataSource(AccessDao.this.getDataSource());
				PreparedStatement pst;
				String st="";
				try {
					pst = jt.getDataSource().getConnection().prepareStatement(
						"INSERT INTO ACCESS(access_id, access_date,   elapsed,  client, log_tag ,   size ,  method , url, proxy) " 
							+ " VALUES(nextval('SEQ_ACCESS_ID'), ?, ?,? ,?,?,?,?, ?)");
					

					LineNumberReader reader = new LineNumberReader(
							new InputStreamReader(is));
					st = reader.readLine();
					while (st != null) {
						String params[] = st.split("[\\ ]+");

						st = reader.readLine();

						long dateLong = (long) (Double.parseDouble(params[0]) * 1000);
						java.sql.Timestamp date = new java.sql.Timestamp(
								dateLong);
						pst.setTimestamp(1, date); // date
						pst.setInt(2, Integer.parseInt(params[1])); // elapses
						pst.setString(3, params[2]); // client
						pst.setString(4, params[3]); // log tag
						pst.setInt(5, Integer.parseInt(params[4])); // size
						pst.setString(6, params[5]); // method
						pst.setString(7, params[6]); // url
						pst.setString(8, proxy);
						pst.execute();
					}

				} catch (Exception e) {
					e.printStackTrace();
					System.err.println("String: " + st);
				}
				
				return null;
			}

		});
		calculateSummary();
	}
	
	public void delete(String proxy)
	{
		AccessExample ex=new AccessExample();
		ex.createCriteria().andProxyEqualTo(proxy);
		getSqlMapClientTemplate().delete("access.abatorgenerated_deleteByExample", ex);
	}
	public void delete()
	{
		AccessExample ex=new AccessExample();
		getSqlMapClientTemplate().delete("access.abatorgenerated_deleteByExample", ex);
	}
}
